﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace SuggestionService
{
    public class SuggestionService : ISuggestionService
    {
        public List<int> GetSuggestedTests(string userId)
        {
            var groupCount = 5;
            var quizCount = 5;
            //Finding similar group
            var similarUsers = SimilarGroupCalculator.FindSimilarityGroup(userId, groupCount);
            
            var allQuizes = new List<QuizTaken>();
            var allTakenQuizes = new Dictionary<string, List<QuizTaken>>();
            foreach (var similarUser in similarUsers)
            {
                var quizes = DataAccess.GetQuizesTakenByUser(similarUser.User.UserId).ToList();
                allTakenQuizes.Add(similarUser.User.UserId, quizes);
                allQuizes.AddRange(quizes);
            }
            allQuizes = allQuizes.GroupBy(q => q.Quiz.QuizId).Select(q => q.First()).ToList();
            
            //Calculating weighted coefficients
            var quizesPopularity = new Dictionary<int, double>();
            for (int i = 0; i < allQuizes.Count; i++)
            {
                int idx = i;
                var curQuiz = allQuizes[i];
                double weight = 0;
                int cnt = 0;
                for (int j = 0; j < similarUsers.Count; j++)
                {
                    var quiz =
                        allTakenQuizes[similarUsers[j].User.UserId].Find(
                            q => q.Quiz.QuizId == allQuizes[idx].Quiz.QuizId);
                    if (quiz != null)
                    {
                        weight += quiz.Scores*similarUsers[j].SimilarityScore;
                        cnt++;
                    }
                }
                quizesPopularity.Add(curQuiz.Quiz.QuizId, cnt == 0 ? 0 : (weight/cnt));
            }
            var result = quizesPopularity.OrderBy(q => q.Value).Take(quizCount).Select(q => q.Key).ToList();
            return result;
        }
        
        public List<User> GetAllUsers()
        {
            var allUsers = DataAccess.GetAllUsers();
            return allUsers;
        }
    }
}
